package com.itsol.gmap.haovd.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.json.simple.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.itsol.gmap.haovd.dao.HaoMapDAO;
import com.itsol.gmap.haovd.entity.UserHao;

@Controller
@RequestMapping("/gmap/hao")
public class HaoMapController {

	@Autowired
	private HaoMapDAO haoMapDAO;

	@Autowired
	ServletContext servletContext;

	@RequestMapping({ "/index", "/", "" })
	public String listContacts(Map<String, Object> map) {
		List<UserHao> listUser = haoMapDAO.listUser();
		map.put("user", new UserHao());
		map.put("userList", listUser);
		String val = "";
		int i = 0;
		int len = listUser.size();
		for (UserHao user : listUser) {

			if (len > 1 && i < len - 1)
				val += "{'id':" + user.getId() + ",'avatar':'"
						+ user.getAvatar() + "','xmap':'" + user.getXmap()
						+ "','ymap':'" + user.getYmap() + "'},";
			else {
				val += "{'id':" + user.getId() + ",'avatar':'"
						+ user.getAvatar() + "','xmap':'" + user.getXmap()
						+ "','ymap':'" + user.getYmap() + "'}";
			}
			i++;
		}

		map.put("userJson", "[" + val + "]");
		return "haovd/haomap";
	}
	
	@RequestMapping(value = "/listjsonuser", method = RequestMethod.GET)
	public @ResponseBody List<UserHao> listUserJsonArray(){
		List<UserHao> listUser = haoMapDAO.listUser();
		return listUser;
	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String getHaoUser(@ModelAttribute("user") UserHao user,
			BindingResult result) {
		haoMapDAO.updateUser(user);
		return "redirect:/gmap/hao/index";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String addHaoUser(@ModelAttribute("user") UserHao user,
			BindingResult result) {
		// UploadFile
		// MultipartHttpServletRequest files = (MultipartHttpServletRequest)
		// request;
		// MultipartFile avatar = files.getFile("avatar");
		// boolean uploaded = fileUpload(avatar);
		// if (uploaded) {
		// user.setAvatar(avatar.getOriginalFilename());
		haoMapDAO.addUser(user);
		// }
		return "redirect:/gmap/hao/index";
		// throw new Exception("Không upload được file Ảnh");
	}

	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String editHaoUser(@RequestParam(value = "img") String img,
			HttpServletRequest request) {
		request.setAttribute("img", img);
		return "haovd/show_avatar";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String fileUpload(HttpServletRequest request) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		MultipartHttpServletRequest files = (MultipartHttpServletRequest) request;
		MultipartFile avatar = files.getFile("avatar");
		String filename = avatar.getOriginalFilename();
		try {
			inputStream = avatar.getInputStream();

			File newFile = new File(servletContext.getRealPath("/")
					+ "resources/haovd/img/" + filename);
			if (!newFile.exists()) {
				newFile.createNewFile();
			}
			outputStream = new FileOutputStream(newFile);
			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
			}
			request.setAttribute("img", filename);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} finally {
			if (outputStream != null)
				try {
					outputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

		}
		return "haovd/show_avatar";
	}

	@RequestMapping("/delete/{userId}")
	public String deleteContact(@PathVariable("userId") Integer userId) {

		haoMapDAO.removeUser(userId);
		return "redirect:/user/index";
	}
}
